// Copyright © 2011 Kris Maglione <maglione.k@gmail.com>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE file included with this file.
"use strict";

const { prefs } = Components.utils.import("resource://exttest/exttest.jsm", {});

function $(selector, node) (node || document).querySelector(selector);

function wrap(fn) {
    return function wrapped() {
        try {
            return fn.apply(this, arguments);
        }
        catch (e) {
            Cu.reportError(e);
        }
    }
}

var edit = {
    onLoad: wrap(function onLoad(event) {
        this.elements = {
            add: $("#add"),
            clear: $("#clear"),
            input: $("#newValue"),
            remove: $("#remove"),
            list: $("#valueList")
        };

        [this.pref, this.title] = window.arguments;
        document.title += " " + this.title;

        this.values = JSON.parse(prefs.safe.get(this.pref, "[]"));

        for each (let value in this.values)
            this.elements.list.appendItem(value, "");

        this.updateButtons();
    }),

    onAccept: wrap(function onSubmit(event) {
        prefs.safe.set(this.pref, JSON.stringify(this.values));
    }),

    onAdd: wrap(function onAdd(event) {
        this.add(this.elements.input.value);
        this.elements.input.value = "";
        this.elements.input.focus();
        this.updateButtons();
    }),
    onClear: wrap(function onClear(event) {
        let list = this.elements.list;
        while (list.firstChild)
            list.removeChild(list.firstChild);
        this.values = [];
    }),
    onRemove: wrap(function onRemove(event) {
        this.elements.list.selectedItems.slice().forEach(function (item) {
            item.parentNode.removeChild(item);
        });
        this.values = Array.map(this.elements.list.children,
                                function (elem) elem.getAttribute("label"));
    }),

    add: function add(value) {
        this.values.push(value);
        this.values.sort();
        this.elements.list.insertItemAt(this.values.indexOf(value), value, "");
        this.updateButtons();
    },
    remove: function remove(index) {
        this.values.splice(index);
        this.elements.list.removeItemAt(index);
    },

    updateButtons: function updateButtons() {
        let elems = this.elements;
        elems.add.disabled = !elems.input.value || this.values.indexOf(elems.input.value) >= 0;
        elems.clear.disabled = !elems.list.children.length;
        elems.remove.disabled = !elems.list.selectedItem;
    }
};
